package com.maxlab.showimage;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.File;
import java.io.FileInputStream;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    @InjectView(R.id.btn_load_from_SD)
    Button btnLoadFromSD;
    @InjectView(R.id.btn_load_from_res)
    Button btnLoadFromRes;
    @InjectView(R.id.iv_show)
    ImageView ivShow;


    /**
     * Environment.getExternalStorageDirectory()得到：“、mnt/sdcard” 即找到了sd卡的根目录
     */
    private String PATH = Environment.getExternalStorageDirectory().toString() + "/Android_Test";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);


        if (isStoragePermissionGranted()) {
            File directory = new File(PATH);
            File[] files = directory.listFiles();
            Log.i(TAG, PATH + " files : " + (files == null ? null : files.length));
        }
    }

    public boolean isStoragePermissionGranted() {
        if (Build.VERSION.SDK_INT >= 23) {
            final Context context = getApplicationContext();
            int readPermissionCheck = ContextCompat.checkSelfPermission(context,
                    Manifest.permission.READ_EXTERNAL_STORAGE);
            int writePermissionCheck = ContextCompat.checkSelfPermission(context,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (readPermissionCheck == PackageManager.PERMISSION_GRANTED
                    && writePermissionCheck == PackageManager.PERMISSION_GRANTED) {
                Log.v(TAG, "Permission is granted");
                return true;
            } else {
                Log.v(TAG, "Permission is revoked");
                ActivityCompat.requestPermissions(this, new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                return false;
            }
        } else { //permission is automatically granted on sdk<23 upon installation
            Log.v(TAG, "Permission is granted");
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.v(TAG, "onRequestPermissionsResult requestCode ： " + requestCode
                + " Permission: " + permissions[0] + " was " + grantResults[0]
                + " Permission: " + permissions[1] + " was " + grantResults[1]
        );
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //resume tasks needing this permission
            File directory = new File(PATH + "/Android_Test");
            File[] files = directory.listFiles();
            Log.i(TAG, "After PERMISSION_GRANTED files : " + (files == null ? null : files.length));
        }
    }

    /**
     * 从本地加载Bitmap
     *
     * @param path
     * @return
     */
    public static Bitmap loadNativeImage(String path) {
        try {
            FileInputStream fis = new FileInputStream(path);
            Bitmap bitmap = BitmapFactory.decodeStream(fis);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 从Res加载Bitmap
     *
     * @param context 如
     * @param resId   如 R.drawable.lena
     * @return
     */
    public static Bitmap loadResImage(Context context, int resId) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        TypedValue value = new TypedValue();
        context.getResources().openRawResource(resId, value);
        options.inTargetDensity = value.density;
        options.inScaled = false;
        return BitmapFactory.decodeResource(context.getResources(), resId, options);
    }

    @OnClick({R.id.btn_load_from_SD, R.id.btn_load_from_res})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_load_from_SD: {
                String filePath = PATH + "/child.jpg";
                Bitmap bm = loadNativeImage(filePath);
                Log.d(TAG, "onClick: " + bm);
                ivShow.setImageBitmap(bm);
                break;
            }

            case R.id.btn_load_from_res: {
//                Bitmap bm = BitmapFactory.decodeResource(getResources(),
//                        R.drawable.lena); // 获取bitmap【项目资源目录】
                Bitmap bm = loadResImage(this, R.drawable.lena);
                ivShow.setImageBitmap(bm);
                break;
            }

        }
    }
}
